//
//  VideoListTableViewController.swift
//  LearnDemo
//
 //  Created by 振轩 on 2018/4/4.
//  Copyright © 2018年 振轩. All rights reserved.
//
let videoList = "VideoList"

import UIKit
class headerTitle: UIView {
    var titleLabel:UILabel?
    var targetBtn:UIButton?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
   func setUpUI(){
        titleLabel = UILabel(frame: CGRect(x: 5, y: 0, width: 200, height: 30))
        //titleLabel?.backgroundColor =
        targetBtn = UIButton(frame: CGRect(x: kScreenW-100, y: 0, width: 60, height: 30))
        targetBtn?.setImage(UIImage.init(named: "loginarror"), for: .normal)
        titleLabel?.font = UIFont.systemFont(ofSize: 13)
        titleLabel?.text = "全部"
        addSubview(titleLabel!)
        addSubview(targetBtn!)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
class VideoListTableViewController: SwiftBaseTableViewController {
    var data:[ArticleMode]? = [ ArticleMode]()
    //数据请求对象模型。
    var ReqCou:CourseListReq = CourseListReq()
    var categ:Categorys?{
        didSet{
            var array :[String] = [String]()
            for a in (categ?.child)!{
                
                let c :Cate = a as! Cate
                array.append(c.name!)
                
            }
            suTitle = array
            ReqCou.catId = (categ?.id)!
        }
        
    }
    
    var suTitle:[String]?
    
    fileprivate var titleView:headerTitle={
        
        let headerTitl = headerTitle(frame: CGRect(x:10, y: 0, width: kScreenW, height: 30))
        headerTitl.backgroundColor = UIColor.white
        headerTitl.targetBtn?.addTarget(self, action: #selector(isSpan), for: .touchUpInside)
        //headerTitl.backgroundColor = UIColor.red
        return headerTitl
        
    }()
    var hisVie: HistoryWordsView = {
        let HisView =    HistoryWordsView(frame: CGRect(x: 15, y: 30, width: kScreenW-30, height: 100))
        HisView.backgroundColor = UIColor.white
        return HisView
        
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UINib(nibName: "VideoListCell", bundle: nil), forCellReuseIdentifier: "VideoList")
        tableView.rowHeight = 194
        //self.tableView .addSubview(titleView)
        self.tableView.tableHeaderView = titleView
        self.tableView.headerView(forSection: 0)
        self.tableView.addSubview(hisVie)
        hisVie.historyWordsArr = self.suTitle
        hisVie.isHidden = true
        hisVie.delegate = self
        //[MBProgressHUD, showActivityMessageInView:@"加载中..." timer:10.0];
        MBProgressHUD.showActivityMessage(inView: "数据正在加载中")
        loadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return (self.data?.count) ?? 0
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "VideoList", for: indexPath) as! VideoListCell
        cell.mode = data?[indexPath.row]
        
        

       

        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let mode :ArticleMode = data![indexPath.row]
        let vc = LiveViewControllerViewController()
        let mode1:ReqMode = ReqMode()
        
        mode1.courseId = mode.id
       
        mode1.staffId = LoginStatuesModel.getStaffId()
        mode1.staffType = LoginStatuesModel.getUserType()
        vc.ReqM = mode1
        present(vc, animated: true, completion: nil)
        
        
    }
    @objc func isSpan(){
        hisVie.isHidden = !hisVie.isHidden
    }
    override func loadData(){
        self.ReqCou.currentPage = self.currentPage
        let params:[String:AnyObject] = self.ReqCou.getDic()
        print(params)
        
        //初始化对话框，置于当前的View当中
        //defaultShow(isHide: false)
       
        let API:BaseReqApi = BaseReqApi.init(requestUrl: "/index.php/FoodCheckApi/courseList.json", andrequestTime: 5, andParams: params as [AnyHashable : Any], andRequestMethod: YTKRequestMethod.POST, andCache: false, andCacheTime: 0, andPostToken: true)
        
        API.starRequest { (status, mess, response) in
            
            guard let dic:Dictionary = response as? [String : AnyObject] else{
                return
            }
            print(dic)
            
            if status.rawValue == 1  {
                
                let mode1  = CourseListMode.init(DIC: dic)
                //self.data = mode1.data as? [ArticleMode]
                
                if self.isLoadmore {
                    
                    self.data = self.data! + (mode1.data as? [ArticleMode])!
                    
                }else{
                    
                     self.data = mode1.data as? [ArticleMode]
                    
                }
                //self.data?.removeAll();
                if self.data?.count == 0{
                    
                    self.Datatype = REQuestDataType.NODATAType
                }else{
                    
                    self.Datatype = REQuestDataType.NORMALLType
                }
                
                
                if (mode1.data?.count)! < self.PageSize{
                    self.isFinish = true
                    
                    self.tableView.mj_footer.resetNoMoreData()
                    
                }
                //self.defaultShow(isHide: true)
                self.Count = (self.data?.count)!
                self.tableView.reloadData()
                MBProgressHUD.hide()
                
            }
        }
    }
}
extension VideoListTableViewController:HistoryWordsViewDelegate{
    func historyWordHasBeenClicked(_ keyWord: String!, select index: Int32) {
        self.titleView.titleLabel?.text = keyWord
        isSpan()
        
        let index1:NSInteger = NSInteger(index)
        var currentID:NSInteger = 0
        //let cat:Cate = (self.categ?.child![index1])! as! Cate
        for cate in (self.categ?.child)!{
            let cate1:Cate  = cate as! Cate
            if cate1.name == keyWord{
                
               print(cate1.id)
                print(cate1.name ?? "rtt")
               currentID = cate1.id
               break
            }
        }
        
        ReqCou.catId = currentID
        header.beginRefreshing()
    }
    func defaultShow(isHide:Bool){
        
        var hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud?.labelText = "数据正在加载中"
        //背景渐变效果
        hud?.dimBackground = true
        
        //延迟隐藏
        hud?.hide(true, afterDelay: 1)
        hud?.show(true)
        if isHide {
            hud?.hide(true)
            hud?.removeFromSuperview()
            hud = nil
        }
    }
   
}
